package com.beilang.hotline.template.manager.impl;

import com.beilang.base.codelookup.manager.CodeLookupMgr;
import com.beilang.base.pagination.PaginationHelper;
import com.beilang.base.util.CodeConstant;
import com.beilang.base.util.Constant;
import com.beilang.base.util.ReportUtil;
import com.beilang.base.util.StringUtil;
import com.beilang.hotline.template.dao.TemplateDAO;
import com.beilang.hotline.template.manager.TemplateMgr;
import com.beilang.hotline.template.model.TemplateModel;
import com.beilang.hotline.template.to.SearchTO;
import jxl.Workbook;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WriteException;

import java.io.File;
import java.util.*;

@SuppressWarnings("unchecked")
public class TemplateMgrImpl implements TemplateMgr {

    private TemplateDAO templateDAO;

    private CodeLookupMgr codeLookupMgr;

    public void setCodeLookupMgr(CodeLookupMgr codeLookupMgr) {
        this.codeLookupMgr = codeLookupMgr;
    }

    public void setTemplateDAO(TemplateDAO templateDAO) {
        this.templateDAO = templateDAO;
    }

    public TemplateModel createTemplate(TemplateModel templateModel) {
        return templateDAO.createTemplate(templateModel);
    }

    public TemplateModel saveTemplate(TemplateModel templateModel) {
        return templateDAO.saveTemplate(templateModel);
    }

    public void deleteTemplate(Long templateId) {
        templateDAO.deleteTemplate(templateId);
    }

    public TemplateModel getTemplate(Long templateId) {
        TemplateModel templateModel = templateDAO.getTemplate(templateId);
        if (templateModel != null) {
            templateModel.setSysName(codeLookupMgr.getCodeDesc(CodeConstant.SYS_NAME, templateModel.getSysId().toString()));
        }
        return templateModel;
    }

    public PaginationHelper getTemplateList(PaginationHelper helper, SearchTO searchTO) {
        int count = templateDAO.searchCount(searchTO);
        helper.setTotalSize(count);
        List list = templateDAO.searchList(helper, searchTO);
        if (list != null && list.size() > 0) {
            List l = new ArrayList();
            for (Object obj : list) {
                TemplateModel templateModel = (TemplateModel) obj;
                templateModel.setSysName(codeLookupMgr.getCodeDesc(CodeConstant.SYS_NAME, templateModel.getSysId().toString()));
                l.add(templateModel);
            }
            helper.setList(l);
        } else {
            helper.setList(list);
        }
        return helper;
    }

    public void deleteAllSysTemplates(Long sysId) {
        templateDAO.deleteAllSysTemplates(sysId);
    }

    public byte[] genereateTemplateReport(SearchTO searchTO) {
        byte[] buf = new byte[0];
        String fileName = "";
        try {
            fileName = getRandomFileName();
            File file = new File(Constant.FILEPATH + fileName);

            jxl.write.WritableWorkbook wwb = Workbook.createWorkbook(file);
            jxl.write.WritableSheet ws = wwb.createSheet("模版", 0);
            writeTemplateExcelHeader(ws);
            List list = templateDAO.searchList(searchTO);

            if (list != null && !list.isEmpty()) {
                Iterator itor = list.iterator();
                int row = 1;
                while (itor.hasNext()) {
                    TemplateModel templateModel = (TemplateModel) itor.next();
                    writeTemplateExcelDetail(templateModel, ws, row);
                    row++;
                }
            }

            formatSheet(ws);

            wwb.write();
            wwb.close();
            ReportUtil reportUtil = new ReportUtil();
            buf = reportUtil.readByteArrayOfSpecifiedFile(Constant.FILEPATH + fileName);
            if (file.exists()) {
                file.delete();
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return buf;
    }

    public  void writeTemplateExcelDetail(TemplateModel templateModel,jxl.write.WritableSheet ws,int row) {
        try {
            jxl.write.Label label1 = new jxl.write.Label(0, row,String.valueOf(row), getCell(false));
            String systemName =codeLookupMgr.getCodeDesc(CodeConstant.SYS_NAME, templateModel.getSysId().toString());
            jxl.write.Label label2 = new jxl.write.Label(1, row, StringUtil.deNull(systemName), getCell(false));
            jxl.write.Label label3 = new jxl.write.Label(2, row, StringUtil.deNull(templateModel.getTemplateName()), getCell(false));
            jxl.write.Label label4 = new jxl.write.Label(3, row, StringUtil.deNull(templateModel.getTitle()), getCell(false));
            jxl.write.Label label5 = new jxl.write.Label(4, row, StringUtil.deNull(templateModel.getRecordRemarks()), getCell(false));
            jxl.write.Label label6 = new jxl.write.Label(5, row, StringUtil.deNull(templateModel.getRecordReason()), getCell(false));

            ws.addCell(label1);
            ws.addCell(label2);
            ws.addCell(label3);
            ws.addCell(label4);
            ws.addCell(label5);
            ws.addCell(label6);
        } catch (WriteException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

     public static void formatSheet(jxl.write.WritableSheet ws ) {
             for (int i = 0; i < 6; i++) {
                 if (i==4||i==5)
                 {
                     ws.setColumnView(i, 100);
                 }else if(i==0)
                {
                    ws.setColumnView(i, 10);
                } else 
                 {
                    ws.setColumnView(i, 20);
                 }
            }
     }

    public void writeTemplateExcelHeader(jxl.write.WritableSheet ws) {
        try {
            jxl.write.Label label1 = new jxl.write.Label(0, 0, "序号", getCell(true));
            jxl.write.Label label2 = new jxl.write.Label(1, 0, "系统名", getCell(true));
            jxl.write.Label label3 = new jxl.write.Label(2, 0, "模版名", getCell(true));
            jxl.write.Label label4 = new jxl.write.Label(3, 0, "标题名", getCell(true));
            jxl.write.Label label5 = new jxl.write.Label(4, 0, "问题描述及回复", getCell(true));
            jxl.write.Label label6 = new jxl.write.Label(5, 0, "问题原因", getCell(true));

            ws.addCell(label1);
            ws.addCell(label2);
            ws.addCell(label3);
            ws.addCell(label4);
            ws.addCell(label5);
            ws.addCell(label6);
        } catch (WriteException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

    }

    public String getRandomFileName() {
        Date cur = new Date();
        Calendar cld = Calendar.getInstance();
        cld.setTime(cur);
        int mth = cld.get(Calendar.MONTH) + 1;
        String nowStr = cld.get(Calendar.YEAR) + "" + mth + cld.get(Calendar.DATE) + cld.get(Calendar.HOUR) + cld.get(Calendar.MINUTE) + cld.get(Calendar.SECOND);
        Random rdm = new Random();
        String rdmNum = String.valueOf(rdm.nextInt());
        return nowStr + rdmNum + Constant.EXCEL_EXTENSION;
    }

    public WritableCellFormat getCell(boolean isBold) {

        WritableFont font = null;
        if (isBold) {
            font = new WritableFont(WritableFont.TIMES, 12, WritableFont.BOLD);
        } else {
            font = new WritableFont(WritableFont.TIMES, 12, WritableFont.NO_BOLD);
        }


        try {
            font.setColour(Colour.BLACK);
        } catch (WriteException e1) {
            e1.printStackTrace();
        }
        WritableCellFormat format = new WritableCellFormat(font);
        try {
            format.setAlignment(jxl.format.Alignment.LEFT);
            format.setVerticalAlignment(jxl.format.VerticalAlignment.TOP);
            format.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
        } catch (WriteException e) {
            e.printStackTrace();
        }
        return format;
    }
}
